/*
 * 点评记录JS
 * 2018-02-13
 */
var reviewRecord = (function(){
	var pageSize = 10,currPage = 1;
	var initPage = function(){
		var dd = new Date().Format("yyyy-MM-dd");
    	$("#sdate").val(dd);
        $("#edate").val(dd);
		$("select").select2();
	}
	 /**
     * 1 处方点评记录接口
     */
    var initReviewList = function(){
        var def = $.Deferred();
        var bdate = "'"+$("#sdate").val()+"'";
        var edate = "'"+$("#edate").val()+"'";
        var param = {params:JSON.stringify({sqlId:16502,bdate:bdate,edate:edate})};
        $.ajax({
        	type: "GET",
        	url: hostUrl+"/basicinformationquery/basequery",
        	data:param,
        	dataType: "json",
        	success: function (resp) {
        		def.resolve(resp.list);
        	}
        });
        return def.promise();
    }
    /*
     * 2 审核处方接口
     */
    var initlookThrought = function(qaa01){
    	debugger;
    	var def = $.Deferred();
    	 var params = {
    			 qaa01:qaa01,
    	 		 bce01:bce01,
    	 		 bce03:trueName
    	 }
    	 var param = {
    			 procId:"quality_qaa1_audit",
    			 params:JSON.stringify(params)
  		 };
    	$.ajax({
    		type: "POST",
    		url: hostUrl+"/basicinformationquery/updateProc",
    		data:param,
    		dataType: "json",
    		success: function (resp) {
    			def.resolve(resp.list);
    		}
    	});
    	return def.promise();
    }
    /*
     * 3 删除处方点评接口
     */
    var qualityQaa1Del = function(data){
    	var def = $.Deferred();
    	var params = {
    			qaa01:data.qaa01,
    			mode:data.mode,
    			bce01:bce01,
    			bce03:trueName,
    			qab01:data.qab01?data.qab01:0
    	}
    	var param = {
    			procId:"quality_qaa1_del",
    			params:JSON.stringify(params)
    	};
    	$.ajax({
    		type: "POST",
    		url: hostUrl+"/basicinformationquery/updateProc1",
    		data:param,
    		dataType: "json",
    		success: function (resp) {
    			def.resolve(resp);
    		}
    	});
    	return def.promise();
    }
    /*
     * 4 处方点评明记录明细接口
     */
    var detailRecord = function(){
    	var info = getParam("review_item");
    	var def = $.Deferred();
    	var param = {params:JSON.stringify({sqlId:16503,qaa01:info.qaa01})};
    	$.ajax({
    		type: "get",
    		url: hostUrl+"/basicinformationquery/basequery",
    		data:param,
    		dataType: "json",
    		success: function (resp) {
    			def.resolve(resp.list);
    		}
    	});
    	return def.promise();
    }
    /*
     * 5 处方明细接口
     */
    var detailItem = function(){
    	var info = getParam("record_detail_table");
    	var def = $.Deferred();
    	var param = {params:JSON.stringify({sqlId:16504,cbm01:info.cbm01})};
    	$.ajax({
    		type: "get",
    		url: hostUrl+"/basicinformationquery/basequery",
    		data:param,
    		dataType: "json",
    		success: function (resp) {
    			def.resolve(resp.list);
    		}
    	});
    	return def.promise();
    }
    /*
     * 6 处方点评人员接口
     */
    var prescriptionStaff = function(){
    	var def = $.Deferred();
    	var txt = "'%"+""+"%'";
    	var param = {params:JSON.stringify({sqlId:10000063,txt:txt})};
    	$.ajax({
    		type: "get",
    		url: hostUrl+"/basicinformationquery/basequery",
    		data:param,
    		dataType: "json",
    		success: function (resp) {
    			def.resolve(resp.list);
    		}
    	});
    	return def.promise();
    }
    /**
     * 显示处方列表
     */
//    var showReviewList = function(){
//    	layer.msg('查询中....', {icon: 16,shade: [0.1, '#393D49'],time:1*500});
//    	$.when(
//    			initReviewList()
//	        ).done(function (data) {
//	          showReviewTable(data)
//	    });
//    }
    var showReviewList = function(){
    	var tname = 'review_item';
    	var bdate = "'"+$("#sdate").val()+"'";
        var edate = "'"+$("#edate").val()+"'";
        var param = {params:JSON.stringify({sqlId:16502,bdate:bdate,edate:edate,currPage:currPage,pageSize:pageSize})};
    	$('#review_item_container').resize(function(){
    		$("#"+tname).setGridWidth($("#review_item_container").width()*1);
    	});
        jQuery('#'+tname).GridUnload();
        jQuery("#"+tname).jqGrid({
        	url : hostUrl+"/basicinformationquery/basequeryPage",
        	postData : param,
        	mtype : 'get',
        	datatype : "json",
            colModel :
                [
                    {label: '单号',name: 'qaa02',  align: 'center', width: '120'},
                    {label: '点评人',name: 'bce03',  align: 'center', width: '60'},
                    {label: '点评日期',name: 'qaa05',  align: 'center', width: '150'},
                    {label: 'A',name: 'qaa07',  align: 'center', width: '60'},
                    {label: 'B',name: 'qaa08',  align: 'center', width: '60'},
                    {label: 'C',name: 'qaa09',  align: 'center', width: '60'},
                    {label: 'D(%)',name: 'qaa10',  align: 'center', width: '60'},
                    {label: 'E',name: 'qaa11',  align: 'center', width: '60'},
                    {label: 'F(%)',name: 'qaa12',  align: 'center', width: '60'},
                    {label: 'G',name: 'qaa13',  align: 'center', width: '60'},
                    {label: 'H(%)',name: 'qaa14',  align: 'center', width: '60'},
                    {label: 'I',name: 'qaa15',  align: 'center', width: '60'},
                    {label: 'J(%)',name: 'qaa16',  align: 'center', width: '60'},
                    {label: 'K',name: 'qaa17',  align: 'center', width: '60'},
                    {label: 'L',name: 'qaa18',  align: 'center', width: '60'},
                    {label: 'O',name: 'qaa19',  align: 'center', width: '60'},
                    {label: 'P(%)',name: 'qaa20',  align: 'center', width: '60'},
                    {label: '状态',name: 'qaa06',  align: 'center', width: '60',
                    	formatter:function(cellvalue, options, rowObject){
                            switch (cellvalue)
                            {
                              case 0 :
                                return "未审核";
                                break;
                              case 1 :
                              	return "已审核";
                              	break;
                              case 9 :
                                return "删除";
                                break;
                              default :
                                return "";
                                break;
                            }
                          },
                    
                    },
                    {label: '操作',name: 'mange',  align: 'center',width: '80',
	                	 cellattr: function(rowId, tv, rawObject, cm, rdata) {
	                         return 'id='+tname+'_mange' + rowId;
	                	 }
                    },
                    {label:'qaa01',name:'qaa01',hidden:true},
                ],
            rowNum : pageSize,
            height : 'auto',
            width : "auto",
            autowidth : true,
        	forceFit:true,
            shrinkToFit:true,
        	rownumbers : true,
            beforeSelectRow : function(rowid, e){

            },
            onSelectRow : function(id,status){
            	prescriptRecordDetail();
            },
            loadComplete : function(data)
            {

            	debugger;
            	var ids = jQuery("#"+tname).jqGrid('getDataIDs');
    			for (var i = 0; i < ids.length; i++)
    			{
    				var cl = ids[i];
    				var rowData = $("#"+tname).jqGrid("getRowData",cl);
    				var copyInput;
    				if(rowData.qaa06 == "已审核"){
    				    copyInput = "<button class='btn btn-min btn-resver' disabled='true'>审核</button>";
    					copyInput += "<button class='btn btn-min btn-resver' onclick='reviewRecord.deleteReviewItem("+cl+","+tname+",0)' >删除</button>";
    				}else{
    					copyInput = "<button class='btn btn-min btn-resver' onclick='reviewRecord.lookThroughtItem("+cl+")' >审核</button>";
    					copyInput += "<button class='btn btn-min btn-resver' onclick='reviewRecord.deleteReviewItem("+cl+","+tname+",0)' >删除</button>";
    				}
    				jQuery("#"+tname).jqGrid('setRowData', ids[i],{mange : copyInput});
    			}
    			loadPage(currPage);
    			$("#"+tname).jqGrid("setSelection", 1); //选择第一行，必须要写在分页之后
            },
        })
    };
    //分页
    var loadPage = function(curr){
    	var tname = 'review_item';
		var totalRecord = $("#"+tname).jqGrid('getGridParam', 'records');
		$('#'+tname+'_total').text(totalRecord);
		if (totalRecord <= 0) {
			var $tr = $('#'+tname).find('tbody>tr:last');
			if($tr.length){
				var len = $tr.find('td').length;
				len = parseInt(len);
				$tr.after($('<tr><td colspan="'+len+'" style="text-align:left;">没有符合条件的数据！</td></tr>'));
			}
			return;
		}
		var rowscount = pageSize;
		var totalPage = 1;
		var totalyu = parseInt(totalRecord) % parseInt(rowscount);
		if (totalyu == 0) {
			totalPage = parseInt(totalRecord) / parseInt(rowscount);
		}
		else {
			totalPage = parseInt(totalRecord - totalyu) / parseInt(rowscount) + 1
		}

		laypage(
			{
				cont: 'review_page', // 容器。值支持id名、原生dom对象，jquery对象。【如该容器为】：<div id="page1"></div>
				pages: totalPage, // 通过后台拿到的总页数
				curr: curr || 1, // 当前页
				skip: true, // 是否开启跳页
				jump: function (obj, first) { // 触发分页后的回调
					if (!first) { // 点击跳页触发函数自身，并传递当前页：obj.curr
						currPage = obj.curr;
						loadPage(currPage);

					}
				}
			});
		reloadGrid(curr);

	}
	var reloadGrid = function(pageNumber){
		var bdate = "'"+$("#sdate").val()+"'";
	    var edate = "'"+$("#edate").val()+"'";
		if(pageNumber==undefined||pageNumber==''){
			pageNumber = 1;
		}
		  var param = {params:JSON.stringify({sqlId:16502,bdate:bdate,edate:edate,currPage:currPage,pageSize:pageSize})};
		jQuery("#review_item").jqGrid('setGridParam',
			{
				url: hostUrl+"/basicinformationquery/basequeryPage",
				postData: param,
				datatype: "json",
				mtype: "GET"
			}).trigger('reloadGrid');// 重新载入
	    }
    //审核--
    var lookThroughtItem = function(rowId){
    	event.stopPropagation();
    	layer.confirm('确认审核当前点评记录吗？？', {
    		  btn: ['确认','取消'] //按钮
    		}, function(){
    			var tname = 'review_item';
    	    	var rowData = $("#"+tname).jqGrid("getRowData",rowId);
    	    	layer.msg('审核中....', {icon: 16,shade: [0.1, '#393D49'],time:1*500});
    	    	$.when(
    	    			initlookThrought(rowData.qaa01)
    		        ).done(function (data) {
    		        	layer.msg("审核成功", {time : 3000,icon : 1,skin: 'layui-layer-msg1'});
    		        	showReviewList();
    		    });
    		}, function(){
    		});
    }
    //删除处方列表--
    var deleteReviewItem = function(rowId,tname,mode){
    	event.stopPropagation();
    	layer.confirm('确认删除当前点评记录吗？', {
    		  btn: ['确认','取消'] //按钮
    		}, function(){
    	    	var rowData = $(tname).jqGrid("getRowData",rowId);
    	    	rowData.mode = mode;
    	    	layer.msg('删除中....', {icon: 16,shade: [0.1, '#393D49'],time:1*500});
    	    	$.when(
    	    		qualityQaa1Del(rowData)
    	    	).done(function (data) {
    	    		if(data.result == "Success"){
    	    			layer.msg("删除成功", {time : 3000,icon : 1,skin: 'layui-layer-msg1'});
    	    			if(mode == 1){
    	    				prescriptRecordDetail();
    	    			}
    	    			showReviewList();
    	    		}else{
    	    			layer.alert(data.resultMsg, {icon : 0});
    	    		}
    	    	});
    		}, function(){
    			
    			
    		});
    }
    var getParam = function(tname){
		var selectedId = $("#"+tname).jqGrid("getGridParam", "selrow");
		var rowData = false;
		if(selectedId){
			rowData = $("#"+tname).jqGrid("getRowData", selectedId);
		}
    	return rowData;
	}
    //处方点评记录明细
    var prescriptRecordDetail = function(){
    	layer.msg('查询中....', {icon: 16,shade: [0.1, '#393D49'],time:1*500});
    	$.when(
    		 detailRecord()
    	).done(function (data) {
    		debugger;
    		prescriptRecordDetailTable(data);
    	});
    }
    var prescriptRecordDetailTable = function(arr){
    	var tname = 'record_detail_table';
    	$('#record_detail_container').resize(function(){
    		$("#"+tname).setGridWidth($("#record_detail_container").width()*1);
    	});
        jQuery('#'+tname).GridUnload();
        jQuery("#"+tname).jqGrid({
            datatype: 'local',
            data:arr,
            colModel :
                [
                    {label: '处方日期',name: 'qab06', width: '115'},
                    {label: '处方号',name: 'cbm01', width: '110'},
                    {label: '病人姓名',name: 'vaa05', width: '55'},
                    {label: '性别',name: 'abw02', width: '30'},
                    {label: '年龄（岁）',name: 'agep', width: '40'},
                    {label: '处方诊断',name: 'qab10',width: '120'},
                    {label: '药品品种',name: 'qab11',width: '30'},
                    {label: '抗菌处方用药',name: 'qab15',width: '40'},
                    {label: '注射剂处方',name: 'qab14',  align: 'center',editable : true,edittype : 'checkbox',formatter : 'checkbox', width: '60',
                    	editoptions :
    					{
    						value : "1:0",
    						defaultValue: 0
    					}
                    },
                    {label: '国家基本药物品种数',name: 'qab13', width: '40'},
                    {label: '药品通用名数',name: 'qab12',width: '40'},
                    {label: '处方金额',name: 'qab16', width: '60'},
                    {label: '处方医师',name: 'bce03a', width: '60'},
                    {label: '审核调配药师',name: 'bce03b', width: '40'},
                    {label: '核对发药药师',name: 'bce03c', width: '40'},
                    {label: '是否合理',name: 'qab22',  align: 'center',editable : true,edittype : 'checkbox',formatter : 'checkbox', width: '30',
                    	editoptions :
    					{
    						value : "1:0",
    						defaultValue: 0
    					}
                    },
                    {label: '存在问题因素',name: 'blk04', width: '160'},
                	{label: '存在问题编码',name: 'blk02', width: '40'},
                    {label: '备注',name: 'bck03b', width: '50'},
                    {label: '操作',name: 'mange',  align: 'center',width: '50',
	                	 cellattr: function(rowId, tv, rawObject, cm, rdata) {
	                         return 'id='+tname+'_mange' + rowId;
	                	 }
                   },
                    {label: 'qab01',name: 'qab01',  hidden: true},
                    {label: 'qaa01',name: 'qaa01',  hidden: true},
                    {label: 'vaa01',name: 'vaa01',  hidden: true},
                    {label: 'bce01',name: 'bce01',  hidden: true},
                    {label: 'recordid',name: 'recordid',  hidden: true},
                    {label: 'acf01',name: 'acf01',  hidden: true},
                    {label: 'bck01',name: 'bck01',  hidden: true},
                    {label: 'bce03',name: 'bce03',  hidden: true},
                    {label: 'vaa07',name: 'vaa07',hidden:true},
                    {label: 'qab06',name: 'qab06',hidden:true},
                ],
            height : 'auto',
            width : "auto",
            autowidth : true,
        	forceFit:true,
            shrinkToFit:true,
            onSelectRow : function(id,status){
            	prescriptItemDetail();
            },
            loadComplete : function(data)
            {
            	var ids = jQuery("#"+tname).jqGrid('getDataIDs');
    			for (var i = 0; i < ids.length; i++)
    			{
    				var cl = ids[i];
    				var rowData = $("#"+tname).jqGrid("getRowData",cl);
    				var copyInput = "<button class='btn btn-min btn-resver' onclick='reviewRecord.deleteReviewItem("+cl+","+tname+",1)' >删除</button>";
    				jQuery("#"+tname).jqGrid('setRowData', ids[i],{mange : copyInput});
    			}
            },
        })
    }
    //处方明细
    var prescriptItemDetail = function(){
    	layer.msg('查询中....', {icon: 16,shade: [0.1, '#393D49'],time:1*500});
    	$.when(
    		  detailItem()
    	).done(function (data) {
    		debugger;
    		showDetailTable(data);
    	});
    }
    //处方明细展示 -- 表格
    var showDetailTable = function(arr){
    	var tname = 'item_detail_table';
    	$('#item_detail_container').resize(function(){
    		$("#"+tname).setGridWidth($("#item_detail_container").width()*1);
    	});
        jQuery('#'+tname).GridUnload();
        jQuery("#"+tname).jqGrid({
            datatype: 'local',
            data:arr,
            colModel :
                [
                    {label: '组',name: 'cbm01', width: '100'},
                    {label: '序号',name: 'rownr', width: '30'},
                    {label: '医嘱内容',name: 'vaf22', width: '200'},
                    {label: '剂量',name: 'vaf20', width: '40'},
                    {label: '单位',name: 'bdg02', width: '40'},
                    {label: '总量',name: 'vaf21', width: '40'},
                    {label: '单位',name: 'funit', width: '40'},
                    {label: '频次',name: 'vaf26', width: '60'},
                    {label: '嘱托',name: 'vaf23', width: '80'},
                    {label: '执行时间方案',name: 'vaf30', width: '80'},
                    {label: '执行性质',name: 'vaf58',width: '80',
                	 formatter:function(cellvalue, options, rowObject){
                         switch (cellvalue)
                         {
                           case 0 :
                              return "正常";
                              break;
                           case 1 :
                           	  return "自备药";
                           	  break;
                           case 2 :
                              return "离院带药";
                              break;
                           case 3 :
                           	  return "医技单独生成条码 ";
                           	  break;
                           case 4 :
                    	      return "院外执行 ";
                    	      break;
                           case 5 :
                        	  return "外配处方 ";
                        	  break;
                           default :
                              return "";
                              break;
                         }
                	 }
                    },
                    {label: '执行科室	',name: 'bck03b', width: '80'},
                    {label: '滴速',name: 'vaf60', width: '60'},
                    {label: '备注',name: 'vaf55', width: '80'},
                ],
            rowNum : arr.length,
            height : 'auto',
            width : "auto",
            autowidth : true,
        	forceFit:true,
            shrinkToFit:true,
        	rownumbers : true,
            beforeSelectRow : function(rowid, e){

            },
            onSelectRow : function(id,status){
            },
            loadComplete : function(data)
            {
            	noDataRemaind(data,tname);
            },
        })
    }
    //字义含义说明模块
    var theWordMean = function(){
    	laytplUrl(myUrl + "/tpl/word_mean.html",{}, function(data, html) {
			var index = layer.open({
				type : 1,
				title : "字义含义说明",
				area : [ "600px", "350px" ],
				shade : 0.1,
				 maxmin : true,
				content : html,
				closeBtn : 1,
				success : function() {
				}
			})

		});
    }
    var noDataRemaind = function(data,tname){
    	if(data.records == 0){
			var $tr = $('#'+tname).find('tbody>tr:last');
			var len = $tr.find('td').length;
			$("#"+tname).html('<tr><td colspan="'+ parseInt(len)+ '" style="text-align:left;">没有符合条件的数据！</td></tr>');
		}
    }
    var initInfo = function(){
        initPage();    //初始化时间
        showReviewList();
    }
    return {
        initInfo:initInfo,
        showReviewList:showReviewList,
        lookThroughtItem:lookThroughtItem,
        deleteReviewItem:deleteReviewItem,
        theWordMean:theWordMean,
        getParam:getParam,
    }
}());
$(function(){
	reviewRecord.initInfo();
});